package com.shqcjd.yunweiyanoperator.ui.activity.staff;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.orhanobut.logger.Logger;
import com.shqcjd.yunweiyanoperator.R;
import com.shqcjd.yunweiyanoperator.api.ApiService;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxObserver;
import com.shqcjd.yunweiyanoperator.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.yunweiyanoperator.model.ResponseData;
import com.shqcjd.yunweiyanoperator.model.pojo.ExpertDetailBean;
import com.shqcjd.yunweiyanoperator.model.pojo.NormalUserBean;
import com.shqcjd.yunweiyanoperator.ui.activity.ExpertInfoActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.ShareActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.WaitingAnswerActivity;
import com.shqcjd.yunweiyanoperator.ui.activity.remote.DeviceListActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BaseActivity;
import com.shqcjd.yunweiyanoperator.ui.base.BasePresenter;
import com.shqcjd.yunweiyanoperator.util.PrefUtils;
import com.shqcjd.yunweiyanoperator.util.ToastUtils;
import com.shqcjd.yunweiyanoperator.widget.thumbup.ThumbUpView;
import com.shqcjd.yunweiyanoperator.widget.thumbup.ThumbView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 联系人详情
 */
public class ContactsDetailsActivity extends BaseActivity {


    @BindView(R.id.btn_finish)
    ImageView btnFinish;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.tv_type)
    Button tvType;
    @BindView(R.id.tv_phone_number)
    TextView tvPhoneNumber;
    @BindView(R.id.rl_send_guide)
    RelativeLayout rlSendGuide;
    @BindView(R.id.rl_add)
    RelativeLayout rlAdd;
    @BindView(R.id.rl_share_list)
    RelativeLayout rl_share_list;
    @BindView(R.id.rl_expert_info)
    RelativeLayout rl_expert_info;
    @BindView(R.id.tv_include_add)
    TextView tv_include_add;
    @BindView(R.id.thumbup)
    ThumbUpView thumbup;
    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    private int remoteId;
    private boolean isAddFriends;
    private String acceptAppCode;
    private Context mContext;
    private int friendId;
    private String userName;
    ArrayList<String> mTypeVals = new ArrayList<>();
    private int followed;//1:已关注,0:未关注 ,
    private ExpertDetailBean expertDetailData;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_contacts_details;
    }

    @Override
    public void initView() {
        mContext = this;
        isAddFriends = getIntent().getBooleanExtra("isAddFriends", false);
        friendId = getIntent().getIntExtra("friendId", -1);
        remoteId = getIntent().getIntExtra("remoteId", -1);
        acceptAppCode = getIntent().getStringExtra("acceptAppCode");


        if (isAddFriends) {
            tvTitle.setText("专家详情");
            rlSendGuide.setVisibility(View.GONE);
            rlAdd.setVisibility(View.VISIBLE);
        } else {
            tvTitle.setText("好友详情");
            rlSendGuide.setVisibility(View.VISIBLE);
            rlAdd.setVisibility(View.GONE);

        }

        if (acceptAppCode.equals("expert")) {//专家
            //获取专家详情
            getExpertDetail();
            rl_expert_info.setVisibility(View.VISIBLE);
            tv_include_add.setVisibility(View.VISIBLE);
            tv_include_add.setText("关注");
            Drawable drawableLeft = getResources().getDrawable(R.drawable.ic_guanzhu_n);
            tv_include_add.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,null, null, null);
            tv_include_add.setTextColor(ContextCompat.getColor(mContext,R.color.topbar_user));
            tv_include_add.setCompoundDrawablePadding(4);
        } else {
            //获取操作员详情
            getUserDetail();
            rl_expert_info.setVisibility(View.GONE);
        }


    }


    /**
     * 设置关注view的显示
     * @param isFollow
     */
    private void setFollowView(boolean isFollow) {
        if (tv_include_add == null) {
            return;
        }
        if (isFollow) {//已关注
            tv_include_add.setText("已关注");
            Drawable drawableLeft = getResources().getDrawable(R.drawable.ic_guanzhu_y);
            tv_include_add.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,null, null, null);
            tv_include_add.setTextColor(ContextCompat.getColor(mContext,R.color.topbar_user));
            tv_include_add.setCompoundDrawablePadding(4);
        } else {//未关注
            tv_include_add.setText("关注");
            Drawable drawableLeft = getResources().getDrawable(R.drawable.ic_guanzhu_n);
            tv_include_add.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,null, null, null);
            tv_include_add.setTextColor(ContextCompat.getColor(mContext,R.color.topbar_user));
            tv_include_add.setCompoundDrawablePadding(4);
        }
    }

    /**
     * 取消关注
     */
    private void cancelFollow() {
        Map<String, String> map = new HashMap<>();
        map.put("userAppCode", acceptAppCode);
        map.put("userId", friendId+"");
        ApiService.cancelFollow(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode == 10000) {
                            setFollowView(false);
                            followed = 0;//1:已关注,0:未关注 ,
                        } else {
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showLong(mContext,errorMessage);
                    }
                });
    }

    /**
     * 设置关注
     */
    private void setFollow() {
        Map<String, String> map = new HashMap<>();
        map.put("userAppCode", acceptAppCode);
        map.put("userId", friendId+"");
        ApiService.follow(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode == 10000) {
                            followed = 1;//1:已关注,0:未关注 ,
                            setFollowView(true);
                            ToastUtils.showLong(mContext, "关注成功");
                        } else {
                            ToastUtils.showLong(mContext, "关注失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showLong(mContext,errorMessage);
                    }
                });
    }

    /**
     * 用户点赞
     */
    private void userLike(){
        Map<String, String> map = new HashMap<>();
        map.put("userAppCode", acceptAppCode);
        map.put("userId", friendId+"");
        ApiService.userLike(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode == 10000) {
                        } else {

                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showLong(mContext,errorMessage);
                    }
                });

    }

    /**
     * 取消点赞
     */
    private void cancelLike() {
        Map<String, String> map = new HashMap<>();
        map.put("userAppCode", acceptAppCode);
        map.put("userId", friendId+"");
        ApiService.cancelUserLike(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onNext(ResponseData responseData) {

                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showLong(mContext,errorMessage);
                    }
                });
    }

    @OnClick({R.id.btn_finish, R.id.rl_send_guide, R.id.rl_add,R.id.rl_share_list,R.id.rl_expert_info,R.id.tv_include_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.rl_send_guide://发起指导
                showSelectCamera();
                break;
            case R.id.rl_add://添加好友
                showOutDialog();
                break;
            case R.id.rl_share_list://指导分享记录
                Intent intent = new Intent(ContactsDetailsActivity.this, ShareActivity.class);
                intent.putExtra("remoteId", friendId);
                intent.putExtra("acceptAppCode", acceptAppCode);
                startActivity(intent);
                break;
            case R.id.rl_expert_info://专家资料
                Intent expertIntent = new Intent(mContext, ExpertInfoActivity.class);
                expertIntent.putExtra("performance",expertDetailData.performance);
                expertIntent.putExtra("honor",expertDetailData.honor);
                expertIntent.putExtra("technicalCertificate",expertDetailData.technicalCertificate);
                startActivity(expertIntent);
                break;
            case R.id.tv_include_add://关注用户
                if (followed == 1) { //1:已关注,0:未关注 ,
                    cancelFollow();
                } else {
                    setFollow();
                }
                break;
        }
    }


    /**
     * 选择摄像头
     */
    private void showSelectCamera(){
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_select_camera, false)
                .show();
        View customeView = dialog.getCustomView();

        TextView phone = customeView.findViewById(R.id.tv_phone);
        TextView externalCamera = customeView.findViewById(R.id.tv_external_camera);
        phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Intent intent = new Intent(ContactsDetailsActivity.this, WaitingAnswerActivity.class);
                intent.putExtra("remoteId", remoteId);
                intent.putExtra("friendId", friendId);
                intent.putExtra("acceptAppCode", acceptAppCode);
                intent.putExtra("acceptUserName", userName);
                startActivity(intent);
            }
        });
        externalCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();

                Intent intent = new Intent(ContactsDetailsActivity.this, DeviceListActivity.class);
                intent.putExtra("remoteId", remoteId);
                intent.putExtra("friendId", friendId);
                intent.putExtra("acceptAppCode", acceptAppCode);
                intent.putExtra("acceptUserName", userName);
                startActivity(intent);
            }
        });
    }


    private void showOutDialog() {
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_add_view, false)
                .show();

        View customeView = dialog.getCustomView();

        TextView cancel = customeView.findViewById(R.id.tv_cancel);
        TextView confirm = customeView.findViewById(R.id.tv_confirm);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                addContactsHttp(friendId + "", userName);
            }
        });
    }

    /**
     * 添加好友
     */
    private void addContactsHttp(String friendId, String friendName) {
//        String appcode = PrefUtils.getString(mContext, PrefUtils.APPCODE, "");
        Map<String, String> map = new HashMap<>();
        map.put("friendAppCode", acceptAppCode);
        map.put("friendId", friendId);
        map.put("friendName", friendName);
        ApiService.addContacts(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode == 10000) {
                            ToastUtils.showShort(mContext, "添加好友的请求已经发送给对方");
                        } else {
                            ToastUtils.showShort(mContext, responseData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, "发送失败");
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }


    /**
     * 设置专家用户详情view的显示
     * @param data
     */
    private void setExpertDetailsView(ExpertDetailBean data){
        tvName.setText(data.userName);//姓名
        tvCompany.setText(data.businessName);//企业
        tvPhoneNumber.setText(data.phoneNumber);//电话
        if (data.followed == 1) {//1:已关注,0:未关注 ,
            setFollowView(true);
        } else {
            setFollowView(false);
        }
        if (data.liked == 1) {//1:已点赞,0:未点赞 ,
            thumbup.setCount(data.likeNum).setThumbUp(true);
        } else {
            thumbup.setCount(data.likeNum).setThumbUp(false);
        }

        thumbup.setThumbUpClickListener(new ThumbView.ThumbUpClickListener() {
            @Override
            public void thumbUpFinish() {//点赞成功
                userLike();
            }

            @Override
            public void thumbDownFinish() {//取消点赞
                cancelLike();
            }
        });



        TagAdapter tagAdapter = new TagAdapter<String>(mTypeVals.toArray(new String[mTypeVals.size()])) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.tv_major_tag,
                        flowlayout, false);
                tv.setText(s);
                return tv;
            }

        };
        flowlayout.setAdapter(tagAdapter);
    }

    /**
     * 获取专家用户详情
     */
    private void getExpertDetail(){
        Map<String, Integer> map = new HashMap<>();
        map.put("userId",friendId);
        ApiService.getExpertDetails(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ExpertDetailBean>>() {
                    @Override
                    public void _onNext(ResponseData<ExpertDetailBean> retData) {
                        if (retData.retCode == 10000) {
                            expertDetailData = retData.data;
                            userName = retData.data.userName;
                            followed = retData.data.followed;
                            if (retData.data.major != null && retData.data.major.size() > 0) {
                                mTypeVals.clear();
                                for (ExpertDetailBean.MajorBean majorBean : retData.data.major) {
                                    if (majorBean!=null) {
                                        mTypeVals.add(majorBean.name);
                                    }

                                }
                            }
                            //设置显示的页面
                            setExpertDetailsView(retData.data);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }
                });
    }

    /**
     * 获取普通操作员的详情
     */
    private void getUserDetail(){
        Map<String, Integer> map = new HashMap<>();
        map.put("userId",friendId);
        ApiService.getUserDetail(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ExpertDetailBean>>() {
                    @Override
                    public void _onNext(ResponseData<ExpertDetailBean> retData) {
                        if (retData.retCode == 10000) {
                            expertDetailData = retData.data;
                            userName = retData.data.userName;
                            followed = retData.data.followed;
                            if (retData.data.major != null && retData.data.major.size() > 0) {
                                mTypeVals.clear();
                                for (ExpertDetailBean.MajorBean majorBean : retData.data.major) {
                                    mTypeVals.add(majorBean.name);
                                }
                            }
                            //设置显示的页面
                            setExpertDetailsView(retData.data);
                        } else {
                            ToastUtils.showShort(mContext, retData.retMsg);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        ToastUtils.showShort(mContext, errorMessage);
                    }
                });
    }

}
